package org.mifos.boss.ui.controller;

import org.apache.log4j.Logger;
import org.mifos.boss.domainmodel.MobileFileUpload;
import org.mifos.boss.service.BossCollectionServiceInterface;
import org.mifos.boss.service.DataTransferServiceInterface;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;


@Controller
@RequestMapping("/collection")
public class BossCollectionController extends AbstractController {

	static Logger logger = Logger.getLogger(BossCollectionController.class);

	@Autowired
	@Qualifier("bossCollectionService")
	private BossCollectionServiceInterface bossCollectionService;   
	
	@Autowired
	@Qualifier("dataTransferService")
	private DataTransferServiceInterface dataTransferService;
	
	@RequestMapping("/new")
	public String collectData(Model model) {
		logger.debug("Upload data from MFMS Mobile to BOSS");

		model.addAttribute("mobileFileUpload", new MobileFileUpload());
    	return "collection";
	}
	 /**
     * Adds a new customer by delegating the processing to CustomerServiceImpl.
     * Displays a confirmation JSP page
     * 
     * @return  the name of the JSP page
     */
    @RequestMapping(value = "/success")
    public String initiateDataUpload(@ModelAttribute("mobileFileUpload") MobileFileUpload mobileFileUpload, BindingResult result) {
		
    	logger.debug("Received request to process uploaded data");
		
    	if(result.hasErrors()){
    		
    		for(ObjectError error: result.getAllErrors()){
    			logger.error("Error: " + error.getCode() + "-" + error.getDefaultMessage());
    		}
    		//return page for upload fail
    		return "error";
    	}
    	// The "customerData" model has been passed to the controller from the JSP
    	// We use the name "mobileFileUpload" because the JSP uses that name
    			
		// Call method to process xml data
    	dataTransferService.processUploadedData(mobileFileUpload);

		return "datauploadsuccess";
	}
}
